package com.zk.shopping.base.filter;

import com.alibaba.fastjson.JSON;
import com.zk.shopping.base.model.ModelResult;
import com.zk.shopping.base.model.ReturnCodeEnum;
import com.zk.shopping.base.utils.ThreadLocalUtils;
import com.zk.shopping.user.entity.UserEntity;
import nl.bitwalker.useragentutils.UserAgent;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangkai on 16-1-19.
 * 登陆之后才能够访问，否则跳转到登录页面
 */
public class AuthorityFilter implements Filter {

    //    Logger logger = (Logger) LogFactory.getLog(AuthorityFilter.class);
    Map<String, String> exclutionUrlMap = new HashMap<>();

    public void init(FilterConfig filterConfig) throws ServletException {
        String exclutionUrl = filterConfig.getInitParameter("exclutionUrl");
        String[] urls = exclutionUrl.split(",");
        for (String url : urls) {
            exclutionUrlMap.put(url, url);
        }
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();
        String relURI = requestURI.substring(requestURI.indexOf(contextPath) + contextPath.length());

//        logger.info("httpRequest :" + request.getRequestURL());

        //获取Session，验证是否已经登陆
        HttpSession session = request.getSession();
        UserEntity userInfo = (UserEntity) session.getAttribute("userInfo");

        //验证是否正在登陆
        if (!exclutionUrlMap.containsKey(relURI) && userInfo == null) {
            ModelResult<String> result = new ModelResult<>();
            result.setCode(ReturnCodeEnum.NO_LOGIN.code);
            result.setData(ReturnCodeEnum.NO_LOGIN.desc);
            ServletOutputStream outputStream = response.getOutputStream();
            String resultStr = JSON.toJSONString(result);

            outputStream.write(resultStr.getBytes());
        }else {
            //threadlocal
            ThreadLocalUtils.addLoginUserEntity(userInfo);
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
            ThreadLocalUtils.addLoginDevice(userAgent);
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    public void destroy() {

    }
}
